`timescale  1 ns/1 ps

module spi_slave_send_core #
(
    parameter               DATA_W = 8
)
(
    input   wire                clk,
    input   wire                rst,

    input   wire [07:00]        config_reg,

    input   wire                sclk,
    input   wire                scs,
    output  reg                 miso,

    /*
     * 借用axi-stream总线
     */
    output  reg                 s_axi_tready = 1,
    input   wire                s_axi_tvalid,
    input   wire [DATA_W-1:00]  s_axi_tdata
);

reg     [DATA_W-1:00]           data_in_reg;

reg    [1:0]                sclk_r;
wire                        sclk_rise;
wire                        sclk_fall;

assign          sclk_rise = sclk_r[1:0] == 2'b01;
assign          sclk_fall = sclk_r[1:0] == 2'b10;

always @ (posedge clk)
begin
    if(rst)
        sclk_r    <= 2'b00;
    else
        sclk_r    <= {sclk_r[0], sclk};
end

reg    [1:0]            tvalid_r;
wire                    tvalid_rise;
wire                    tvalid_fall;

assign          tvalid_rise = tvalid_r[1:0] == 2'b01;
assign          tvalid_fall = tvalid_r[1:0] == 2'b10;
always @ (posedge clk or negedge rst)
begin
    if(rst)
        tvalid_r    <= 2'b00;
    else
        tvalid_r    <= {tvalid_r[0], s_axi_tvalid};
end

always @ (posedge clk)
begin
    if(rst)
        miso <= 0;
    else if(s_axi_tvalid & s_axi_tready)
        data_in_reg <= s_axi_tdata;
    else
    begin
        case (config_reg[01:00])
        2'b00:
        begin
            if(tvalid_fall | sclk_fall)
            begin
                miso <= data_in_reg[07];
                data_in_reg <= (data_in_reg << 1);
            end
        end
        2'b01:
        begin
            if(sclk_rise)
            begin
                miso <= data_in_reg[07];
                data_in_reg <= (data_in_reg << 1);
            end
        end
        2'b10:
        begin
            if(tvalid_fall | sclk_rise)
            begin
                miso <= data_in_reg[07];
                data_in_reg <= (data_in_reg << 1);
            end
        end
        2'b11:
        begin
            if(sclk_fall)
            begin
                miso <= data_in_reg[07];
                data_in_reg <= (data_in_reg << 1);
            end
        end
        /*code*/
        default:
        begin
            /*code*/
        end
        endcase
    end
end

endmodule
